package chapter1.zyq1_str_obj;

import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;

public class Client2 {
    public static void main(String[] args) {
        Client2 client = new Client2();
        client.start();
    }
    public void start() {
        InetSocketAddress isAddr = new InetSocketAddress("127.0.0.1", 8001);
        Socket socket = new Socket();
        try {
            socket.connect(isAddr,900);
        /*try{
            Socket socket=new Socket("127.0.0.1", 8001);*/
            System.out.println("客户端连接成功，开始会话...\n");

        } catch (Exception e) {
            System.err.println("链接超时");
            return;
           // e.printStackTrace();
        }
        try {
            session(socket);
            socket.close();
            System.out.println("会话结束，客户端关闭连接。");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /*public void session(Socket socket) throws Exception {//这里的s端和c端没有真正收发数据
        for(int i=1;i<=5;i++){//如果用下边的session方法让c端给s端真正发数据，就可以看到数据发送完毕服务端才断开连接
            Thread.sleep(2000);
            System.out.println("模拟：客户端与服务端进行会话(互相发送数据...)");
        }
    }*/
    public void session(Socket socket) throws Exception {
        Thread.sleep(5000);
       PrintWriter pw=new PrintWriter(socket.getOutputStream(),true);
        for(int i=1;i<=5;i++){//c端给s端真正发数据，就可以看到数据发送完毕服务端才断开连接
            Thread.sleep(2000);
            pw.println("给server发送数据： 数据"+i);
            System.out.println("客户端第" + i + "次发送数据");
        }
    }

}